#!/usr/bin/python
# -*- coding:UTF8 -*-
import io
import sys

from pypinyin import lazy_pinyin
from lxml import etree
import requests

sys.stdout = io.TextIOWrapper(sys.stdout.buffer, encoding='gb18030')
# 1.创造汉语拼音网址  南昌
city_name = input('请输入城市名称:')
city_name = lazy_pinyin(city_name, style=0)
city_name = ''.join(city_name)
# print(city_name)
url = 'https://www.tianqi.com/' + city_name + '/'
user_agent = {
    'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/97.0.4692.99 Safari/537.36'}
# 2.今日天气预报
r = requests.get(url=url, headers=user_agent)
r.encoding = 'utf8'
anlytical_data = etree.HTML(r.text)
citys_name = anlytical_data.xpath('//dd[@class="name"]//h1/text()')[0]
citys_week = anlytical_data.xpath('//dd[@class="week"]/text()')[0]
now_temperature = anlytical_data.xpath('//dd[@class="weather"]//p/b/text()')[0]
day_temperature = anlytical_data.xpath('//dd[@class="weather"]//span/text()')[0]
day_weather = anlytical_data.xpath('//dd[@class="weather"]//span/b/text()')[0]
citys_shidu = anlytical_data.xpath('//dd[@class="shidu"]//b/text()')
citys_shidu = ', '.join(citys_shidu)
citys_kongqi = anlytical_data.xpath('//dd[@class="kongqi"]//h5/text()')[0]
citys_pm = anlytical_data.xpath('//dd[@class="kongqi"]//h6/text()')[0]
citys_pm = citys_pm.split(':')[-1]
citys_pm = citys_pm.strip()
citys_sun = anlytical_data.xpath('//dd[@class="kongqi"]//span/text()')
citys_sun = ', '.join(citys_sun)
print(f'{citys_name} 'f'{citys_week}')
print(f'{day_weather}', f'现在气温：{now_temperature}℃', f'全天温度：{day_temperature}')
print(f'{citys_shidu}')
print(f'{citys_kongqi}')
print('PM2.5:', citys_pm, citys_sun)
# 3.查询近3日内的天气预报
reply = input('是否需要查询近几天的天气？是/否：')
if reply == '是' or reply == 'Y' or reply == 'y' or reply == 'yes':
    while True:
        day = input('请输入需要查询的天数，只能查询3天、7天、10天、15天、30天：')
        if day in ['3', '7', '10', '15', '30']:

            url = f'https://www.tianqi.com/{city_name}/{day}/'
            r = requests.get(url=url, headers=user_agent).text
            # print(r)
            # r.encoding = 'utf8'
            anlytical_data = etree.HTML(r)
            date = anlytical_data.xpath('//div[@class="weaul_q weaul_qblue"]/span/text()')
            date = [''.join(date[i:i + 2]) for i in range(0, len(date), 2)]
            date2 = anlytical_data.xpath('//div[@class="weaul_q"]/span/text()')
            date2 = [''.join(date2[i:i + 2]) for i in range(0, len(date2), 2)]
            date = date + date2
            # print(date)
            weather3 = anlytical_data.xpath('//div[@class="weaul_z"]//text()')
            weather3 = [''.join(weather3[i:i + 5]) for i in range(0, len(weather3), 5)]
            for i in range(len(date)):
                print(f'{date[i]}：{weather3[i]}')
            break
        else:
            print('输入错误，请重新输入数字！')
